require 'uri'

class PathsController < ApplicationController
    before_filter :check_referer, :only => ['new']
    before_filter :login_required, :except => ['index', 'show', 'follow', 'browse', 'current']
    
    layout 'default'
    
    ####################################
    # GET /paths
    # GET /paths.xml
    def index 
        @paths = Path.find(:all,
                            :conditions => "published = 't'",
                            :order => "created_at DESC",
                            :limit => 40)
        respond_to do |format|
            format.html # index.rhtml
            format.xml  { render :action => '../shared/paths_xml.rxml', :layout=>false }
            format.rss  { render :action => '../shared/paths_rss.rxml', :layout=>false }
            format.atom { render :action => '../shared/paths_atom.rxml', :layout=>false }
            format.rdf  { render :action => '../shared/paths_rdf.rxml', :layout=>false }
        end  
    end
    
    ####################################
    # GET /paths/1
    # GET /paths/1.xml
    def show        
        @path = Path.find(params[:id])
        @steps = @path.steps.find(:all, :order => "sequence")
        
        respond_to do |format|
            format.html # show.rhtml
            format.xml  { @paths = [@path]; render :action => '../shared/paths_xml.rxml', :layout=>false }
            format.rss  { @paths = [@path]; render :action => '../shared/paths_rss.rxml', :layout=>false }
            format.atom { @paths = [@path]; render :action => '../shared/paths_atom.rxml', :layout=>false }
            format.rdf  { @paths = [@path]; render :action => '../shared/paths_rdf.rxml', :layout=>false }
        end
        
    end
        
    ####################################
    # GET /paths/new
    # Displays the bookmarklet dialog
    # example bookmarklet
    # javascript:(function(){e=encodeURIComponent;w=window;d=document;l=location;u='http://localhost:3000/paths/new?u='+e(l.href)+'&t='+e(d.title);w.onerror=function(){l.href=u;};dgs=d.getSelection;gs=w.getSelection;c=gs?gs():dgs?dgs():d.selection?d.selection.createRange().text:'';if(c==''){de=d.getElementsByName('Description');c=de&&de[0]?c=de[0].content:''}u=u+'&i=18&c='+e(c);l.href=u;})()
    def new
        
        @user = current_user
   
        @page_title = "Add to Path - Make a Path"
        
        # set up a site class for use by form helpers
        @step = Step.new(:title => params['t'] || "Untitled", :uri => params['u'])
        
        # find the list of paths that this user has created
        @paths = Path.find(:all, :conditions => "user_id = #{@user.id}", :order => 'title ASC')
        
        # retrieve the id of the most recently edited path from the browser cookie
        if params[:path_id]
            @most_recent_path_id = params[:path_id].to_i
        else
            @most_recent_path_id = (cookies[:path_id] || 0).to_i
        end
        # bookmarklet dialog uses a custom chrome
        render(:layout => false)
    end
    
    ####################################
    # POST /paths
    # POST /paths.xml
    def create
        @path = Path.new(params[:path])
        
        respond_to do |format|
            if @path.save
                flash[:notice] = 'Path was successfully created.'
                format.html { redirect_to path_url(@path) }
                format.xml  { head :created, :location => path_url(@path) }
            else
                format.html { render :action => "new" }
                format.xml  { render :xml => @path.errors.to_xml }
            end
        end
    end
    
    ####################################
    # GET /paths/1;edit
    def edit
        @path = Path.find(params[:id])
        restrict_access(@path.user, 'admin')
        @steps = @path.steps.find(:all, :order => 'sequence')
    end
    
    ####################################
    # PUT /paths/1
    # PUT /paths/1.xml
    def update
        @path = Path.find(params[:id])
        restrict_access(@path.user, 'admin')
        respond_to do |format|
            if @path.update_path_titles(params[:paths])
                flash[:notice] = 'Path was successfully updated.'
                @path = Path.find(params[:id])
                @steps = @path.steps.find(:all, :order => "sequence")
                format.html { render :action =>"edit" }
                format.xml  { head :ok }
            else
                format.html { render :action => "edit" }
                format.xml  { render :xml => @path.errors.to_xml }
            end
        end
        
    end
    
    ####################################
    # DELETE /paths/1
    # DELETE /paths/1.xml
    def destroy
        @path = Path.find(params[:id])
        restrict_access(@path.user, 'admin')
        
        @path.destroy
        
        respond_to do |format|
            format.html { redirect_to :controller => "users", :action => "paths", :id => current_user.id}
            format.xml  { head :ok }
        end
    end
    
    ####################################
    # Changes whether the object is visible to 
    # the world.
    def change_visibility
        @path = Path.find(params[:id])
        @path.toggle_published_status
        render :partial => "shared/published_link_contents", :object => @path
    end
    
    ####################################
    # Loads the body content with the first trail.
    def current       
        @path = Path.find(params[:id])
        @steps = @path.steps.find(:all, :order => "sequence")
        if @steps.empty?
            render(:layout => false)
        else
            redirect_to @steps[0].link.uri
        end 
    end
    
    ####################################
    # Create a list of paths
    def browse       
        @path = Path.find(params[:id])
        @on_load_script = 'onload="setTimeout(window.location=\'#bottom\', 20000)"' if params[:scroll_to_bottom]
        @steps = @path.steps.find(:all, :order => 'sequence')
        render(:layout => false)
    end
    
    ####################################
    # waits for a second and then redirects to the browse page
    # called after adding a page to a path
    def delayed_browse
        render(:layout => false);
    end
    
    ####################################
    # Append a page to a path (handles the result of submitting the bookmarklet)
    def append_page
        # get the id of the path to add the page to
        path_id = params[:path][:id]
        step_uri = params[:step][:uri]
        
        # an id of -1 means a new path
        if path_id == '-1'
            @path = Path.create!(:title => params[:path][:title], :user => current_user)
        else
            @path = Path.find(path_id)
        end
        
        # append the page to the specified path
        @path.append_step(params[:step][:uri], params[:step][:title])
        
        # store the currently selected path id in a browser cookie
        cookies[:path_id] = @path.id.to_s
        
        # close the bookmarklet dialog        
        respond_to do |format|
            format.html { redirect_to((path_id == '-1') ? "/paths/browse/#{@path.id.to_s}" : step_uri) }
            format.xml  { head :ok }
        end
        
        # go get the thumbnail
        Link.cache_thumbnail(step_uri)
    end
    
    ####################################
    # Append a page to a path (handles the result of submitting from the edit page)
    def add_from_edit
        @path = Path.find(params[:path_id])
        step_uri = params[:uri]
        step_title = params[:title]
        @path.append_step(params[:uri], params[:title])
        @steps = @path.steps.find(:all, :order => "sequence")
        render :partial => "edit_step"
    end
    
    ####################################
    # Close the popup window after appending the page
    def close_popup
        render(:layout => false)
    end
    
    ####################################
    # Called by Ajax.  Updatest the order of each item in the path
    def update_path_order
        @path = Path.find(params[:path_id])
        @path.update_step_order(params['path-list'])
        
        respond_to do |format|
            flash[:notice] = 'Path was successfully updated.'
            format.html { redirect_to path_url(@path) }
            format.xml  { head :ok }
        end
    end
    
    
    private
    ####################################
    # try to auto login the user
    def check_referer
        user = User.find(params[:i]) rescue nil
        
        if !user.nil?

            @current_user = user
            session[:user_id] =  @current_user.id
            # referer = headers['HTTP_REFERER']
            #             debugger
            #             if !referer.nil?
            #                 
            #                 current_user = user
            #             end
        end
    end
                        
end